<template>
	<view class="sleep-index">
		<view class="menu">
			<view class="menu-item f-base flex-no-horizontal m-b-10"
			@click="menuClick(0)" :class="active === 0 ? 'active' : ''">
				<u--image width="16" height="16" class="m-r-10"
				src="https://cdn3.relaverse.cn/appfile/sleep-index-menu1.png"></u--image>
				设置目标
			</view>
			<view class="menu-item f-base flex-no-horizontal m-b-10"
			@click="menuClick(1)" :class="active === 1 ? 'active' : ''">
				<u--image width="16" height="16" class="m-r-10"
				src="https://cdn3.relaverse.cn/appfile/sleep-index-menu2.png"></u--image>
				睡眠分析
			</view>
			<view class="menu-item f-base flex-no-horizontal m-b-10"
			@click="menuClick(2)" :class="active === 2 ? 'active' : ''">
				<u--image width="16" height="16" class="m-r-10"
				src="https://cdn3.relaverse.cn/appfile/sleep-index-menu3.png"></u--image>
				睡眠规则
			</view>
		</view>
		<view class="sleep-content" :class="isMoveRight ? 'move-right' : ''">
			<view class="m-b-20 p-row-20">
				<u-icon :name="isMoveRight ? 'close' : 'list'" color="#B4BAD5" size="19" @click="showMenu"></u-icon>
			</view>
			<view class="clock m-b-30">
				<canvas id="myCanvas" canvas-id="myCanvas"
				:style="{'width': canvas.w + 'px','height': canvas.h + 'px'}">
				</canvas>
			</view>
			<view class="p-row-20">
				<template v-if="sleepData && sleepData.showTime">
					<view class="text-center f-xs " style="color: rgba(194, 224, 230, 0.7);"
					>预计睡眠时间：{{sleepData.showTime}}</view>
					<!-- <view class="set-target set-target-style" @click="toSleep"> -->
					<view class="set-target set-target-style" @click="toSleep" v-if="isShowCountDown">
						<view class="flex-no-horizontal" style="justify-content: center;flex-direction: column;">
							<text class="f-15 bold">点击立即入睡</text>
							 <view class="f-10 flex-no-horizontal" style="opacity: 0.7;">
								 睡眠倒计时
								 <u-count-down
								 @finish="finishCountdown"
								 ref="countDown"
								 :time="countDownStart" format="mm:ss"></u-count-down>
								 后将自动入睡
							 </view>
						</view>
					</view>
					<view class="set-target set-target-style" v-else>
						<view class="flex-no-horizontal" style="justify-content: center;flex-direction: column;">
							<view class="f-15 bold m-b-5">到入睡目标时间后打开APP自动开始</view>
							 <view class="f-10" style="opacity: 0.7;">
								 入睡前15分钟进入页面可开始睡眠
							 </view>
						</view>
					</view>
				</template>
				<view class="set-target" v-else>
					<u-button shape="circle" size="large" @click="toSet"
					class="set-target-height"
					color="linear-gradient(0deg, #0093A0 0%, #00A18C 100%)">
					 <view class="f-15 bold">点击设置睡眠目标</view>
					</u-button>
				</view>
				<view class="challenge" v-if="challenge">
					<view class="challenge-bg"></view>
					<view style="position: relative;z-index: 2;">
						<view class="f-15 text-center bold m-b-15 flex-no-horizontal" style="justify-content: center;">
							<u--image :src="challenge.sleep_icon"
							width="15" height="15" class="m-r-5"></u--image>
							{{challenge.sleep_title}}
						</view>
						<view class="f-xxs text-center m-b-20" style="opacity: 0.7;">
							{{challenge.sleep_description}}
						</view>
						<view class="flex-no-horizontal days m-b-10">
							<view :key="index" class="day"
							:class="{'uncheck': !item.hasFinished, 'gift': item.award_image}"
							:style="item.award_image ? 'background-image: url('+ item.award_image +')':''"
							v-for="(item,index) in challenge.award">
								<u-icon name="checkbox-mark" size="8"
								@click="getAward(item.sleep_id, item.award_id,item.state)"
								:color="item.hasFinished ? 'white' : '#587F89'"></u-icon>
								<view class="gift-tip text-center"
								v-if="item.mayGetShow"
								:class="index == 0 ? 'gift-tip-left' : index == challenge.maximum_days - 1 ? 'gift-tip-right' : 'gift-tip-center'"
								>
									还有{{item.day - challenge.finished_num}}日即可领取
								</view>
								<view class="gift-tip text-center gift-tip-small"
								:class="index == 0 ? 'gift-tip-left' : index == challenge.maximum_days - 1 ? 'gift-tip-right' : 'gift-tip-center'"
								v-else-if="item.state == 1"
								>
									可领取
								</view>
							</view>
						</view>

					</view>
				</view>

			</view>
		</view>
		<u-popup :show="isShowGift" @close="isShowGift = false"
		overlayOpacity="0.9" safeAreaInsetBottom mode="center"
		bgColor="#000000">
			<view class="get-gift" v-if="awardData">
				<u--image class="star star1" src="https://cdn3.relaverse.cn/appfile/sleep-finish-star1.png" width="28"
					height="28"></u--image>
				<u--image class="star star2" src="https://cdn3.relaverse.cn/appfile/sleep-finish-star2.png" width="44"
					height="44"></u--image>
				<view class="text-center get-gift-title m-b-15">领取成功</view>
				<view v-html="awardData.award_tips"></view>
				<view class="flex-no-horizontal center m-b-30">
					<u--image width="100" height="100"
					:src="awardData.award_image"></u--image>
				</view>
				<u-button shape="circle" color="linear-gradient(0deg, #00B0C0 0%, #00CBB1 100%)"
				 @click="isShowGift = false">
					<text class="bold f-base">确认</text>
				</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {getPoint,drawPoint} from '../../utility/canvas.js'
	import {
		ifLoginFun
	} from '../../utility/weChatLogin.js'
	import {configApi,challenge as challengeApi,
	getAward as getAwardApi,
	getTargetApi} from '../../api/sleep.js'
	import {getMintues} from './components/sleep.js'
	import permision from "@/js_sdk/wa-permission/permission.js"
	export default {
		data() {
			return {
				ctx: null,
				canvas: {
					w: 334, h:334
				},
				timer: null,
				isMoveRight: false,
				active: 0,
				isShowGift: false,
				sleepData: null,
				isShowCountDown: false,
				countDownStart: 15 * 60 * 1000,
				sleepTimer: null,
				challenge: null,
				awardData: null,
				hasClick: false
			}
		},
		onLoad() {
			if (!ifLoginFun()) return
			this.sleepData = this.$store.state.sleepData
			this.getConfig()
			this.getChallenge()
		},
		onShow() {
			if (this.ctx) {
				this.timer = setInterval(this.initCanvas,1000)
			}
			this.handleCountDown()
			this.hasClick = false
		},
		async onReady() {
			await this.getTarget()
			this.ctx = uni.createCanvasContext('myCanvas')
			this.handleCountDown()

			// 时间表盘
			this.timer = setInterval(this.initCanvas,1000)

			uni.$on('changeTarget', () => {
				this.sleepData = this.$store.state.sleepData
				this.handleCountDown()
			})
			uni.$on('finish', () => {
				this.countDownStart = 15 * 60 * 1000
				this.isShowCountDown = false
				this.getChallenge()
			})
		},
		onUnload() {
			clearInterval(this.timer)
			clearInterval(this.sleepTimer)
			uni.$off('changeTarget')
			uni.$off('finish')
		},
		onHide() {
			this.isMoveRight = false
			clearInterval(this.timer)
			clearInterval(this.sleepTimer);
		},
		methods: {
			async getTarget() {
				try{
					const res = await getTargetApi()
					if (!res.data) return
					let sleepData = {}
					sleepData.sleep = res.data.start_time
					sleepData.getUp = res.data.end_time
					const {sumMintues, showTime} = getMintues(sleepData.sleep,sleepData.getUp)
					sleepData.sumMintues = sumMintues
					sleepData.showTime = showTime
					sleepData.checked_music = res.data.checked_music
					sleepData.checked_guide = res.data.checked_guide
					sleepData.guide_state = res.data.guide_state
					sleepData.music_state = res.data.music_state
					this.sleepData = sleepData
					this.$store.commit('setSleepTartget', this.sleepData)
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}
			},
			async getChallenge() {
				try{
					const res = await challengeApi()
					let  challenge = res.data
					let award = []
					for(let i = 0; i < res.data.maximum_days; i++) {
						award[i] = {
							state: 3,// 0: 不可领取 1.可领取 2.已领取 3.无奖励
							award_id: 0,
							award_num: 0,
							award_image: '',
							mayGetShow: false,
							sleep_id: null,
							hasFinished: i < res.data.finished_num
						}
					}
					res.data.award.forEach(item => {
						const hasFinished = award[Number(item.day) - 1].hasFinished
						award[Number(item.day) - 1] = {
							hasFinished,
							...item
						}
					})
					let mayGet = []
					award.filter((item,index) => {
						item.state == 0 ? mayGet.push(index) : ''
					})
					if (mayGet.length) {
						award[mayGet[0]].mayGetShow = true
					}
					challenge.award = award
					this.challenge = challenge
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}
			},
			async getAward(sleepId, awardId,state) {
				if (state != 1) return
				if (!(sleepId && awardId)) return
				try{
					const res = await getAwardApi({
						sleep_id: sleepId,
						award_id: awardId
					})
					this.awardData = res.data
					this.isShowGift = true
					this.getChallenge()
				}catch(e){
					uni.showToast({
						title: e.data || e.message,
						icon: 'none'
					})
					//TODO handle the exception
				}
			},
			async getConfig() {
				try{
					const res = await configApi()
					this.$store.commit('setSleepConfig', res.data)
				}catch(e){
					console.log(e)
					//TODO handle the exception
				}
			},
			handleCountDown() {
				if (!this.sleepData || !this.sleepData.sumMintues) return
				const now = new Date()
				const mintues = now.getHours() * 60 + now.getMinutes()
				const getUpMintues = Number(this.sleepData.getUp.split(":")[0] * 60) + Number(this.sleepData.getUp.split(":")[1])
				const sleepMintues = Number(this.sleepData.sleep.split(":")[0] * 60) + Number(this.sleepData.sleep.split(":")[1])
				const remainder = sleepMintues - mintues

				// 是否提前结束睡眠再返回页面
				if (uni.getStorageSync('aheadFinish') && ((getUpMintues > sleepMintues && mintues < getUpMintues) || (getUpMintues < sleepMintues && mintues > getUpMintues))) {
					this.isShowCountDown = false
					return
				}
				uni.removeStorageSync('aheadFinish')
				if (remainder < 0) {
					if ( (getUpMintues > sleepMintues && mintues < getUpMintues) || (getUpMintues < sleepMintues && mintues > getUpMintues)) {
						this.countDownStart = 0
						this.isShowCountDown = true
					} else {
						this.isShowCountDown = false
					}
				} else if (remainder <= 15) {
					// 已经到睡眠时间前15分钟之内
					this.countDownStart = remainder < 0 ? 0 : remainder * 60 * 1000
					this.isShowCountDown = true
				} else {
					// 还未到睡眠时间前15分钟
					this.isShowCountDown = false
					this.sleepTimer = setTimeout(() => {
						this.isShowCountDown = true
						this.countDownStart = 15 * 60 * 1000
					}, (remainder - 15) * 60 * 1000)
				}
			},
			showMenu() {
				this.isMoveRight = !this.isMoveRight
			},
			menuClick(index) {
				this.active = index
				let pageName = null
				switch (index){
					case 0:
						pageName = 'setTarget'
						break;
					case 2:
						pageName = 'sleepRule'
						break;
					default:
						break;
				}
				uni.navigateTo({
					url: `./${pageName}`
				})
			},
			initCanvas() {
				this.ctx.clearRect(0,0,this.canvas.w,this.canvas.h)
				this.ctx.drawImage('https://cdn3.relaverse.cn/appfile/sleep-clock-bg.png',0,0,this.canvas.w,this.canvas.h)
				this.ctx.save()
				this.getTime()
				this.drawArc()
				this.ctx.draw()
			},
			getTime() {
				const now = new Date()
				const hour = now.getHours()
				const minutes = now.getMinutes()
				const theta = Math.PI * 2 * ((hour * 60 + minutes) / (24 * 60))
				this.ctx.save()
				this.ctx.translate(this.canvas.w/2,this.canvas.h/2)
				this.ctx.rotate(theta)
				this.ctx.beginPath()
				this.ctx.arc(0,0,33,0,2*Math.PI)
				this.ctx.clip()
				this.ctx.fillStyle = 'transparent'
				this.ctx.fill()
				this.ctx.drawImage('https://cdn3.relaverse.cn/appfile/zhizhen.png',-33,-33,66,66)
				this.ctx.restore()
			},
			drawArc() {
				const sleepData = this.sleepData
				if (!sleepData) return
				const sleepTime =  sleepData.sleep
				const getUpTime = sleepData.getUp
				if (!sleepTime || !getUpTime) return
				const iconR = 10 // icon的半径
				const R = this.canvas.w/2 - iconR
				const startPoint = {x:this.canvas.w / 2, y: iconR}
				const sleepPoint = getPoint(sleepTime,startPoint.x,startPoint.y,R,24)
				const getUpPoint = getPoint(getUpTime,startPoint.x,startPoint.y,R,24)
				this.ctx.save()
				this.ctx.translate(this.canvas.w/2,this.canvas.h/2)
				this.ctx.beginPath()
				this.ctx.arc(0,0,R,sleepPoint.rad,getUpPoint.rad)
				this.ctx.lineWidth = 5
				const grd = this.ctx.createLinearGradient(sleepPoint.x,sleepPoint.y,getUpPoint.x,getUpPoint.y)
				grd.addColorStop(0, '#00C897')
				grd.addColorStop(1, '#00ABCA')
				this.ctx.setStrokeStyle(grd)
				this.ctx.stroke()
				this.ctx.restore()

				drawPoint(this.ctx,sleepPoint.x,sleepPoint.y, iconR,'transparent','https://cdn3.relaverse.cn/appfile/sleep-sleep-time.png')
				drawPoint(this.ctx,getUpPoint.x,getUpPoint.y, iconR,'transparent','https://cdn3.relaverse.cn/appfile/sleep-getup-time.png')
			},
			drawPoint(time) {
				this.ctx.save()
				const startX = this.canvas.w / 2
				const startY = 4
				this.ctx.beginPath
			},
			toSet() {
				uni.navigateTo({
					url: './setTarget'
				})
			},
			toSleep() {
				this.hasClick = true
				clearInterval(this.timer)
				this.timer = null
				this.ctx = null
				uni.navigateTo({
					url: './sleeping'
				})
			},
			finishCountdown() {
				setTimeout(() =>{
					if (!this.hasClick) {
						this.toSleep()
					}
				}, 2 * 1000)
			},
		}
	}
</script>

<style scoped lang="scss">
	.sleep-index{
		background-color: #1D2938;
		height: 100%;
		padding: 220rpx 0;
		box-sizing: border-box;
		overflow: hidden;
		width: 100vw;
		position: relative;
		.center{
			justify-content: center;
		}
		.menu{
			padding-left: 36rpx;
			padding-right: 36rpx;
			.menu-item{
				color: #B4BAD5;
				padding: 15rpx 45rpx;
				border-radius: 60rpx;
				width: 260rpx;
				box-sizing: border-box;
			}
			.active{
				background-color: rgba(204, 227, 255, 0.05);
			}
		}
		.sleep-content{
			position: absolute;
			width: 100vw;
			top: 0;
			left: 0;
			min-height: 100vh;
			background: url('https://cdn3.relaverse.cn/appfile/sleep-bg.jpg') no-repeat;
			background-size:100% 100% ;
			padding: 40rpx 0;
			box-sizing: border-box;
			transition: all 0.3s;
			padding-top: 100rpx;
			z-index: 2;
		}
		.move-right{
			border-radius: 53rpx;
			transform: scale(0.8);
			filter: brightness(0.5);
			left: 260rpx;
		}
		.clock{
			display: flex;
			justify-content: center;
		}
		.set-target{
			margin: 60rpx auto 54rpx;
			.set-target-height{
				height: 124rpx;
			}
		}
		.set-target-style{
			background: linear-gradient(0deg, #0093A0 0%, #00A18C 100%);
			border-radius: 64rpx;
			padding: 20rpx;
			color: white;
		}
		.challenge{
			border-radius: 15px;
			color: #C2E0E6;
			padding: 60rpx 10rpx 24rpx;
			position: relative;
			overflow: hidden;
			.challenge-bg{
				filter: blur(2px);
				background-color: rgba(20, 74, 89, 0.8);
				position: absolute;
				width: 100%;
				height: 100%;
				top: 0;
				left: 0;
				// background: url('https://cdn3.relaverse.cn/appfile/sleep-bg.jpg') no-repeat;
				// background-attachment: fixed;
				// background-size: contain;
			}
			.days{
				justify-content: space-between;
				position: relative;
				padding: 0 40rpx 40rpx;
				&::after{
					content: '';
					position: absolute;
					height: 1rpx;
					left: 40rpx;
					right: 40rpx;
					background-color: rgba(255, 255, 255, 0.1);
					z-index: -1;
				}
				.day{
					width: 38rpx;
					height: 38rpx;
					background: #007E83;
					border-radius: 50%;
					display: flex;
					justify-content: center;
					align-items: center;
				}
				.uncheck{
					background-color: rgba(47, 96, 111, 1);
				}
				.today{
					width: 66rpx;
					height: 66rpx;
					background: url(https://cdn3.relaverse.cn/appfile/sleep-get.png) no-repeat;
					background-size: 100% 100% ;
				}
				.gift{
					width: 66rpx;
					height: 66rpx;
					background-size: 100% 100% ;
					background-repeat: no-repeat;
					position: relative;
				}
			}
			.gift-tip{
				position: absolute;
				font-size: 9px;
				font-weight: bold;
				color: #FFFFFF;
				background: #009494;
				padding: 5rpx 10rpx;
				border-radius: 30rpx;
				width: 170rpx;
				bottom: -54rpx;
				&::after{
					content: '';
					border: 10rpx solid transparent;
					position: absolute;
					border-bottom-color: #009494;
					top: -18rpx;
				}
			}
			.gift-tip-right {
				right: 0;
				&::after{
					right: 24rpx;
				}
			}
			.gift-tip-left{
				left: 0;
				&::after{
					left: 24rpx;
				}
			}
			.gift-tip-center{
				right: 50%;
				transform: translateX(50%);
				&::after{
					right: calc(50% - 10rpx);
				}
			}

			.gift-tip-small{
				width: 70rpx;
			}

		}
		.get-gift{
			width: 590rpx;
			box-sizing: border-box;
			position: relative;
			background: url(https://cdn3.relaverse.cn/appfile/sleep-popup-bg.png) no-repeat;
			background-size: 100% 100%;
			padding: 75rpx 60rpx 60rpx;
			.star {
				position: absolute;
			}

			.star1 {
				top: -20px;
				left: -20px;
			}

			.star2 {
				top: -45px;
				right: -10px;
			}

			.get-gift-title{
				font-size: 24px;
				font-weight: 800;
				color: #E0E6FF;
				background: linear-gradient(-90deg, #00FFA8 0%, #00F0FF 100%);
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
			}
		}
	}
	.sleep-index ::v-deep {
		.u-count-down__text{
			color: rgba(255,255,255,0.7);
			font-size: 10px;
			margin: 0 10rpx;
		}
	}
</style>
